<script setup lang="ts">
import {useRouter} from 'vue-router';
import {onMounted, reactive, ref} from "vue";
import {addDataSourceApi, findDataSourceListApi} from "@/api/datasource";
import type {Page, Result} from "@/api/common-types.ts";
import type {GlobalDataSource} from "@/api/datasource/type.ts";
import {ElMessage, type FormInstance, type FormRules} from "element-plus";
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import {SM2} from 'gm-crypto';


const router = useRouter();
/**
 * 新增数据源
 */
const dialogFormVisible = ref(false);
const addForm = ref<GlobalDataSource>({
  active: false,
  activeCount: "", dbName: "", driverClassName: "", idleCount: "", url: "",
  dbType: 'MySQL',
  host: 'bj-cynosdbmysql-grp-b4cfxl4m.sql.tencentcdb.com',
  port: '29476',
  username: '',
  password: '',
  key: ''
})

// 数据源类型选项
const dbTypes = [
  {value: 'MySQL', label: 'MySQL'},
  {value: 'Oracle', label: 'Oracle'},
  {value: 'PostgreSQL', label: 'PostgreSQL'},
  {value: 'SQLServer', label: 'SQL Server'}
];
// 校验
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<GlobalDataSource>>({
  key: [
    {required: true, message: '请输入唯一KEY', trigger: 'blur'},
    {min: 4, max: 50, message: '长度为4到50位', trigger: 'blur'},
  ],
})
/**
 * 提交表单
 */
const submitForm = (formEl: FormInstance | undefined) => {
  // 表单验证
  if (!formEl) return
  formEl.validate((valid, fields) => {
    console.log(valid)
    if (valid) {
      // 提交
      addDataSourceApi(addForm.value)
          .then((res: Result<any>) => {
            if (res.status === 200) {
              ElMessage.success(res.message)
              // 关闭对话框
              dialogFormVisible.value = false;
              // 重新加载数据
              fetchData(page.value);
            } else {
              ElMessage.error(res.message)
            }
          })
          .catch(e => {
            console.log('添加数据源失败！错误：' + e);
          })
    } else {
      console.log('error submit!', fields)
    }
  })
};
/**
 * 列表点击
 */
const handleClick = (event: any) => {
  console.log('click')
}
const tableData = ref<GlobalDataSource[]>([]);

// 分页
const page = ref<Page>({
  pageNum: 1,
  pageSize: 10,
  total: 0,
})
// 处理页码变化
const handleCurrentChange = (newPage: number) => {
  page.value.pageNum = newPage;
  fetchData(page.value);
};

// 处理每页条数变化
const handleSizeChange = (newSize: number) => {
  page.value.pageSize = newSize;
  page.value.pageNum = 1; // 重置到第一页
  fetchData(page.value);
};
// 获取数据的方法（支持分页参数）
const fetchData = (page: Page) => {
  findDataSourceListApi(page)
      .then((res: Result<Array<GlobalDataSource>>) => {
        tableData.value = res.data;
        page.total = res.total;
      })
      .catch((e: Error) => {
        console.log("查询数据源列表失败！错误：" + e);
      });
};
const privateKey = 'c472e19629656b1aac05b3d418744df099e0ab5e7333a20055ab0a2a12917065';

// 解密函数
function decryptSM2(ciphertext: string) {
  // 移除 "04" 前缀
  if (ciphertext.startsWith('04')) {
    ciphertext = ciphertext.substring(2);
  }

  try {
    // 调用解密方法
    return SM2.decrypt(
        ciphertext,
        privateKey,
        {
          inputEncoding: 'hex', // 密文格式为十六进制
          outputEncoding: 'utf8' // 输出明文格式
        }
    );
  } catch (error) {
    console.error('SM2 解密失败:', error);
    return null;
  }
}

onMounted(() => {
  fetchData(page.value)
  const encrypted = "c21bc9b31f74ed79859a5995b493cd4965531ddc1927c468fcedcce9423cacb7fa59428f0748616ce66376893cf130f369a81bf258a76bce643c47b3dc51d4812189a5b64118bac47a1c7191435954fdcf4dd10a434dbd0fe355269348da76f615e597826ac7a35e163414b95d1c47686c1021079fc895a6bc4d2eb5bde11406435e6912ab4144b4335105153ecf234d8152f36bb0c3fd525a000b1abe037b1aac13f92862a9de0d145e3c4bde84cc6eca060820f01d7caf4c515c66574fb2f2a9c7ae16661c59ca199b7cf9fb053be01e01ee6dcf267fad7c61317635afd7ec171ce2e454e9b2ea63";
  var decryptSM = decryptSM2(encrypted);
  console.log(decryptSM)
})
</script>

<template>
  <div class="db-main-root">
    <el-row class="mb-4">
      <el-button size="default" type="primary" @click="dialogFormVisible = true">添加数据源</el-button>
    </el-row>
    <el-dialog v-model="dialogFormVisible" title="添加数据源" width="700">
      <el-form
          ref="ruleFormRef"
          :model="addForm"
          label-width="120px"
          :rules="rules">
        <!-- 唯一KEY -->
        <el-form-item label="数据源唯一KEY" required prop="key">
          <el-input v-model="addForm.key" placeholder="请输入唯一标识符" clearable/>
        </el-form-item>

        <!-- 数据源类型 -->
        <el-form-item label="数据源类型">
          <el-select v-model="addForm.dbType" placeholder="请选择数据库类型" style="width: 100%">
            <el-option
                v-for="type in dbTypes"
                :key="type.value"
                :label="type.label"
                :value="type.value"
            />
          </el-select>
        </el-form-item>

        <!-- IP地址和端口（同一行） -->
        <el-form-item label="服务器地址">
          <el-row :gutter="20">
            <el-col :span="16">
              <el-input v-model="addForm.host" placeholder="IP地址或域名" clearable/>
            </el-col>
            <el-col :span="8">
              <el-input v-model="addForm.port" type="number" placeholder="端口号" clearable/>
            </el-col>
          </el-row>
        </el-form-item>
        <!-- 数据库名 -->
        <el-form-item label="数据库名">
          <el-input v-model="addForm.dbName" placeholder="数据库名" clearable/>
        </el-form-item>
        <!-- 用户 -->
        <el-form-item label="用户名">
          <el-input v-model="addForm.username" placeholder="数据库用户名" clearable/>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item label="密码">
          <el-input
              v-model="addForm.password"
              type="password"
              placeholder="数据库密码"
              show-password
              clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <div class="table-container">
      <el-table border :data="tableData" style="width: 100%">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="key" label="KEY" width="150"/>
        <el-table-column prop="dbType" label="类型" width="80"/>
        <el-table-column prop="driverClassName" label="驱动名称" width="200"/>
        <el-table-column prop="url" label="URL"/>
        <el-table-column prop="username" label="用户" width="100"/>
        <el-table-column prop="activeCount" label="连接池活动连接数" width="120"/>
        <el-table-column prop="idleCount" label="连接池空闲连接数" width="120"/>
        <el-table-column fixed="right" label="Operations" width="120">
          <template #default>
            <el-button type="danger" size="small" @click="handleClick"
            >删除
            </el-button
            >
            <!-- <el-button link type="primary" size="small">Edit</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-config-provider :locale="zhCn">
        <el-pagination
            class="pagination-container"
            :current-page="page.pageNum"
            :page-size="page.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="page.total"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </el-config-provider>
    </div>
  </div>
</template>

<style lang="scss">
.db-main-root {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.table-container {
  height: 85%;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .el-table {
    margin: 1rem 0;

    :deep(.el-table__header-wrapper) {
      position: sticky;
      top: 0;
      z-index: 2;
    }
  }

  .pagination-container {
    margin-top: 2rem;
    justify-content: flex-end;
  }
}
</style>